package com.daisuxia.web.service;

import static com.daisuxia.web.pojo.BorrowOrder.STATUS_YYQ;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.baofoo.BaofooCutPayUtil;
import com.daisuxia.constant.CollectionConstant;
import com.daisuxia.constant.Constant;
import com.daisuxia.constant.FuYouConstant;
import com.daisuxia.payRoute.PayQueryRoute;
import com.daisuxia.payRoute.PayRoute;
import com.daisuxia.risk.service.IOutOrdersService;
import com.daisuxia.ts.service.ITsOrdersService;
import com.daisuxia.web.dao.IBorrowOrderDao;
import com.daisuxia.web.dao.IIndexDao;
import com.daisuxia.web.dao.IPaginationDao;
import com.daisuxia.web.dao.IRenewalRecordDao;
import com.daisuxia.web.dao.IRepaymentDao;
import com.daisuxia.web.dao.IRepaymentDetailDao;
import com.daisuxia.web.dao.IUserDao;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.OutOrders;
import com.daisuxia.web.pojo.RenewalRecord;
import com.daisuxia.web.pojo.Repayment;
import com.daisuxia.web.pojo.RepaymentAlipay;
import com.daisuxia.web.pojo.RepaymentDetail;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.pojo.UserContacts;
import com.daisuxia.web.pojo.fuyou.MobilePaySend;
import com.daisuxia.web.test.ThreadPool;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.DtThread;
import com.daisuxia.web.util.GenerateNo;
import com.daisuxia.web.util.HttpUtil;
import com.daisuxia.web.util.P2pUtils;
import com.daisuxia.web.util.PageConfig;
import com.daisuxia.web.util.SendSmsUtil;
import com.daisuxia.web.util.StringUtils;
import com.daisuxia.web.util.ThreadPool3;
import com.daisuxia.web.util.UserPushUntil;
import com.daisuxia.web.util.XmlUtil;
import com.fuiou.mpay.encrypt.DESCoderFUIOU;

import redis.clients.jedis.JedisCluster;

@Service
public class RepaymentService implements IRepaymentService {

	private static Logger logger = Logger.getLogger(RepaymentService.class);
	@Autowired
	private IRepaymentDao repaymentDao;
	@Autowired
	private IRenewalRecordDao renewalRecordDao;
	@Autowired
	private IBorrowOrderDao borrowOrderDao;
	@Autowired
	private IRepaymentDetailDao repaymentDetailDao;
	@Autowired
	private IPaginationDao paginationDao;
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IUserDao userDao;
	@Autowired
	private IIndexDao indexDao;
	@Autowired
	private IUserService userService;
	@Autowired
	private IUserContactsService userContactsService;
	@Autowired
	private IUserBankService userBankService;
	@Autowired
	private IOutOrdersService outOrdersService;
	@Autowired
	private IJsStepRecordService jsStepRecordService;
	@Autowired
	private IRepaymentDetailService repaymentDetailService;
	@Autowired
	private ITsOrdersService tsOrdersService;
	@Autowired
	private IPushUserService pushUserService;

	@Autowired
	JedisCluster jedisCluster;

	@Override
	public List<Repayment> findAll(HashMap<String, Object> params) {
		return null;
	}

	@Override
	public List<RepaymentDetail> findDetailsByRepId(Integer id) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("assetRepaymentId", id);
		return repaymentDetailDao.findParams(params);
	}

	@Override
	public Repayment findOneRepayment(Map<String, Object> params) {
		List<Repayment> repayments = repaymentDao.findParams(params);
		return null != repayments ? repayments.get(0) : null;
	}

	@Override
	public List<Map<String, Object>> findMyLoan(Map<String, Object> params) {
		return repaymentDao.findMyLoan(params);
	}

	@Override
	public Repayment selectByPrimaryKey(Integer id) {
		return repaymentDao.selectByPrimaryKey(id);
	}

	@Override
	public boolean deleteByPrimaryKey(Integer id) {
		return repaymentDao.deleteByPrimaryKey(id) > 0;
	}

	@Override
	public boolean insert(Repayment repayment) {
		return repaymentDao.insert(repayment) > 0;
	}

	@Override
	public boolean insertSelective(Repayment repayment) {
		return repaymentDao.insertSelective(repayment) > 0;
	}

	@Override
	public boolean updateByPrimaryKey(Repayment repayment) {
		return repaymentDao.updateByPrimaryKey(repayment) > 0;
	}

	@Override
	public boolean updateByPrimaryKeySelective(Repayment repayment) {
		return repaymentDao.updateByPrimaryKeySelective(repayment) > 0;
	}

	@Override
	public PageConfig<Repayment> findPage(HashMap<String, Object> params) {
		params.put(Constant.NAME_SPACE, "Repayment");
		return paginationDao.findPage("findParams", "findParamsCount", params, "web");
	}

	/*
	 * @Override public List<Repayment> findParams(Map<String, Object> params) {
	 * return repaymentDao.findParams(params); }
	 */

	@Override
	public List<Repayment> findTaskRepayment(Map<String, Object> params) {
		return repaymentDao.findTaskRepayment(params);
	}

	@Override
	public List<Repayment> findByRepaymentReport(Map<String, Object> params) {
		return repaymentDao.findByRepaymentReport(params);
	}

	@Override
	public List<Repayment> findByRepaymentSmsRemind(Map<String, Object> params) {
		return repaymentDao.findByRepaymentSmsRemind(params);
	}

	@Override
	public List<Repayment> findRepayingByUserId(Integer id) {
		return repaymentDao.findRepayingByUserId(id);
	}

	@Override
	public Map<String, String> findUserPhoneName(Integer id) {
		return repaymentDao.findUserPhoneName(id);
	}

	@Override
	public Map<String, String> findCardNo(Integer id) {
		return repaymentDao.findCardNo(id);
	}

	@Override
	public Integer findUserIdByPhone(String userPhone) {
		return repaymentDao.findUserIdByPhone(userPhone);
	}

	//正常代扣
	@Override
	public ServiceResult withhold(Repayment re, User user, int withholdType) {
		ServiceResult serviceResult = new ServiceResult("-101", "代扣失败");
		try {
			PayRoute payRoute = new PayRoute(outOrdersService);
			UserCardInfo info = userService.findUserBankCard(Integer.parseInt(user.getId()));

			Long money = (re.getRepaymentAmount() - re.getRepaymentedAmount());
			// 代扣
			String orderNo = "";
			Map map = payRoute.getCutPay(re, user, info, null);
			String retCode = map.get("resp_code").toString();// 返回码
			String ourOrders = map.get("payCutType").toString();//代扣方式
			List errorCodes = (List) map.get("errorCodes");//错误码
			orderNo = map.get("orderNo").toString();//订单号
			if (!retCode.isEmpty()) {

				withholdEle1(errorCodes, re, map, user, orderNo, money, retCode, serviceResult, ourOrders);

			}
		} catch (Exception e) {
			logger.error("withhold error repaymentId=" + re.getId(), e);
			serviceResult = new ServiceResult("-100", "代扣失败");
		}
		return serviceResult;
	}

	/**
	 * @param errorlist     错误码集合 一般覆盖可查询的错误
	 * @param re            贷款信息
	 * @param map           代扣http请求返回map集合
	 * @param user          用户
	 * @param orderNo       订单号
	 * @param money         代扣金额
	 * @param retCode       成功码
	 * @param serviceResult 返回结果集
	 * @param ourOrders     代扣方式
	 */
	public void withholdEle1(
			List errorlist,
			Repayment re,
			Map map,
			User user,
			String orderNo,
			long money,
			String retCode,
			ServiceResult serviceResult,
			String ourOrders) {
		Date currentDate = new Date();
		// 加签
		//String sginOrigin = map.get("qbm_signParam").toString();
		/*String signParam = map.get("qbm_signParam").toString();//请求参数


		OutOrders outOrders = new OutOrders();
		outOrders.setUserId(user.getId());
		outOrders.setAssetOrderId(re.getId());
		outOrders.setOrderType(ourOrders);
		outOrders.setOrderNo(orderNo);
		outOrders.setAct(OutOrders.ACT_DEBIT);
		outOrders.setReqParams(signParam);
		//outOrders.setNotifyParams(sginOrigin);
		outOrdersService.insert(outOrders);*/

		//生成待还
		RepaymentDetail detail = new RepaymentDetail();
		detail.setUserId(re.getUserId());
		detail.setAssetRepaymentId(re.getId());
		detail.setTrueRepaymentMoney(money);
		detail.setOrderId(orderNo);
		detail.setRepaymentType(RepaymentDetail.TYPE_BANK_CARD_AUTO);
		detail.setRemark("定时任务代扣");
		detail.setStatus(RepaymentDetail.STATUS_WAIT);
		detail.setAssetOrderId(re.getAssetOrderId());
		detail.setCreatedAt(currentDate);
		repaymentDetailService.insertSelective(detail);

		OutOrders newOutOrders = new OutOrders();


		newOutOrders.setOrderNo(orderNo);
		newOutOrders.setReturnParams(map.toString());

		logger.error(ourOrders + "_FRONT_DEBIT_RETURN:userId=" + user.getId() + "&repaymentId=" + re.getId() + "&code=" + retCode);
		if ("0000".equals(retCode)) {
			logger.error("repaymentService withhold success repayId=" + re.getId() + " detailId=" + detail.getId() + " orderNo=" + orderNo);
			newOutOrders.setStatus(OutOrders.STATUS_SUC);
			detail.setStatus(RepaymentDetail.STATUS_SUC);
			this.repay(re, detail);

			// 如果是未逾期的还款，调用提额
			if (re.getLateDay() == 0) {
				user = userService.searchByUserid(re.getUserId());
				logger.info("repay to Mention Money ing ----------------->");
				borrowOrderService.addUserLimit(user);
			}
		} else if(errorlist.contains(retCode)){
			newOutOrders.setStatus(OutOrders.STATUS_WAIT);
		}else{
			detail.setStatus(RepaymentDetail.STATUS_OTHER);
			newOutOrders.setStatus(OutOrders.STATUS_OTHER);
		}


		if (null != detail.getStatus()) {
			repaymentDetailService.updateByPrimaryKeySelective(detail);
		}
		outOrdersService.updateByOrderNo(newOutOrders);
	}


	// 交易非成功状态
	public void withholdEle_error_baofoo(List errorList, Repayment re, String orderNo, OutOrders newOutOrders, String retCode, RepaymentDetail newDetail, ServiceResult serviceResult, RepaymentDetail detail) {
		if (errorList.contains(retCode)) {
			logger.error("repaymentService withhold need query repayId=" + re.getId() + " detailId=" + detail.getId() + " orderNo=" + orderNo);
			serviceResult = new ServiceResult("100", "代扣交易处理中");
			newOutOrders.setStatus(OutOrders.STATUS_WAIT);
		} else {
			logger.error("repaymentService withhold failed repayId=" + re.getId() + " detailId=" + detail.getId() + " orderNo=" + orderNo);
			newOutOrders.setStatus(OutOrders.STATUS_OTHER);
			newDetail.setStatus(RepaymentDetail.STATUS_OTHER);
		}
	}

	/*
	@Override
	public ServiceResult withhold(Repayment re, User user, int withholdType) {
		ServiceResult serviceResult = new ServiceResult("-101", "代扣失败");
		try {
			String repayment_no = null;
			SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
			UserCardInfo info = userService.findUserBankCard(Integer.parseInt(user.getId()));

			Long money = (re.getRepaymentAmount() - re.getRepaymentedAmount());
			// 签约
			String orderNo, sginOrigin, signParam, result;
			Map<String, String> intervalMap = SysCacheUtils.getConfigMap(BackConfigParams.WEBSITE);
			orderNo = GenerateNo.getUUID();
			LianlianGrantSend li = new LianlianGrantSend();
			li.setOid_partner(LianLianConstant.getOidPartner());
			li.setUser_id(user.getId());
			li.setRepayment_no(orderNo);
			li.setRepayment_plan("{\"repaymentPlan\":[{\"date\":\"" + format1.format(new Date()) + "\",\"amount\":\""
					+ ((re.getRepaymentAmount() - re.getRepaymentedAmount()) / 100.00) + "\"}]}");
			li.setSms_param("{\"contract_type\":\"\u501f\u6709\u9053\",\"contact_way\":\"" + intervalMap.get("service_phone") + "\"}");
			li.setNo_agree(info.getAgreeno());
			// 加签
			sginOrigin = LLPayUtil.genSignDataByJavaObject(li);
			li.setSign(RSAUtil.sign(LianLianConstant.getKey(), sginOrigin));
			signParam = JSONUtil.beanToJson(li);

			result = HttpUtil.getInstance().postJson(LianLianConstant.getGrantPath(), signParam);
			LianlianGrantRecv grantRecv = JSONUtil.jsonToBean(result, LianlianGrantRecv.class);
			OutOrders outOrders = new OutOrders();
			String tablelastName = DateUtil.getDateFormat(new Date(), "yyyyMMdd");
			outOrders.setUserId(user.getId());
			outOrders.setAssetOrderId(re.getId());
			outOrders.setOrderType(OutOrders.TYPE_LIANLIAN);
			outOrders.setOrderNo(orderNo);
			outOrders.setAct(OutOrders.ACT_GRANT);
			outOrders.setReqParams(signParam);
			outOrders.setNotifyParams(sginOrigin);
			outOrders.setReturnParams(result);
			outOrders.setStatus(OutOrders.STATUS_SUC);
			outOrders.setTablelastName(tablelastName);
			outOrdersService.insertByTablelastName(outOrders);
			logger.error("LIANLIAN_FRONT_GRANT_RETURN:userId=" + user.getId() + "&orderId=" + outOrders.getId() + "" + "&repaymentId="
					+ re.getId() + "&code=" + grantRecv.getRet_code());
			if ("0000".equals(grantRecv.getRet_code())) {
				repayment_no = grantRecv.getRepayment_no();
				if (StringUtils.isNotBlank(repayment_no)) {
					// 代扣
					orderNo = GenerateNo.getUUID();

					Date currentDate = new Date();
					LianlianDebitSend ll = new LianlianDebitSend();
					ll.setUser_id(user.getId());
					ll.setNo_order(orderNo);
					ll.setOid_partner(LianLianConstant.getOidPartner());
					ll.setMoney_order("" + (money / 100.00));
					ll.setNotify_url("http://super.xianjinxia.com/repayment/debit-back");
					ll.setValid_order("120");
					ll.setNo_agree(info.getAgreeno());
					ll.setRepayment_no(repayment_no);
					ll.setDt_order(DateUtil.getDateFormat(currentDate, "yyyyMMddHHmmss"));
					String risk = "{'frms_ware_category':'2010','user_info_mercht_userno':'" + user.getId() + "','user_info_bind_phone':'"
							+ user.getUserPhone() + "','user_info_dt_register':'" + format2.format(user.getCreateTime()) + "','user_info_full_name':'"
							+ user.getRealname() + "','user_info_id_no':'" + user.getIdNumber()
							+ "','user_info_identify_type':'1','user_info_identify_state':'1'}";
					ll.setRisk_item(risk);
					// 加签
					sginOrigin = LLPayUtil.genSignDataByJavaObject(ll);
					ll.setSign(RSAUtil.sign(LianLianConstant.getKey(), sginOrigin));
					signParam = JSONUtil.beanToJson(ll);


					outOrders = new OutOrders();
					outOrders.setUserId(user.getId());
					outOrders.setAssetOrderId(re.getId());
					outOrders.setOrderType(OutOrders.TYPE_LIANLIAN);
					outOrders.setOrderNo(orderNo);
					outOrders.setAct(OutOrders.ACT_DEBIT);
					outOrders.setReqParams(signParam);
					outOrders.setNotifyParams(sginOrigin);
					outOrdersService.insert(outOrders);

					//生成待还
					RepaymentDetail detail = new RepaymentDetail();
					detail.setUserId(re.getUserId());
					detail.setAssetRepaymentId(re.getId());
					detail.setTrueRepaymentMoney(money);
					detail.setOrderId(orderNo);
					detail.setRepaymentType(RepaymentDetail.TYPE_BANK_CARD_AUTO);
					detail.setRemark("定时任务代扣");
					detail.setStatus(RepaymentDetail.STATUS_WAIT);
					detail.setAssetOrderId(re.getAssetOrderId());
					detail.setCreatedAt(currentDate);
					repaymentDetailService.insertSelective(detail);

					OutOrders newOutOrders = new OutOrders();
					RepaymentDetail newDetail = new RepaymentDetail();
					newDetail.setId(detail.getId());

					result = HttpUtil.getInstance().postJson(LianLianConstant.getDebitPath(), JSONUtil.beanToJson(ll));
					JSONObject jsonObject = JSONObject.fromObject(result);

					newOutOrders.setOrderNo(orderNo);
					newOutOrders.setReturnParams(result);

					logger.error("LIANLIAN_FRONT_DEBIT_RETURN:userId=" + user.getId() + "&orderId=" + outOrders.getId() + "" + "&repaymentId=" + re.getId() + "&code=" + jsonObject.getString("ret_code"));
					String retCode = jsonObject.getString("ret_code");
					System.out.println(retCode);
					if ("0000".equals(retCode)) {
						logger.error("repaymentService withhold success repayId=" + re.getId() + " detailId=" + detail.getId() + " orderNo=" + orderNo);
						serviceResult = new ServiceResult(ServiceResult.SUCCESS, "成功");
						newOutOrders.setStatus(OutOrders.STATUS_SUC);
						newDetail.setStatus(RepaymentDetail.STATUS_SUC);
						this.repay(re, detail);
						// 如果是未逾期的还款，调用提额
						if (re.getLateDay() == 0) {
							user = userService.searchByUserid(re.getUserId());
							logger.info("repay to Mention Money ing ----------------->");
							borrowOrderService.addUserLimit(user);
						}
					}
					else if("2008".equals(retCode) || "2004".equals(retCode) || "2005".equals(retCode)){
						logger.error("repaymentService withhold 2008 repayId=" + re.getId() + " detailId=" + detail.getId() + " orderNo=" + orderNo);
						serviceResult = new ServiceResult("100", "代扣交易处理中");
						newOutOrders.setStatus(OutOrders.STATUS_WAIT);
					}
					else {
						logger.error("repaymentService withhold failed repayId=" + re.getId() + " detailId=" + detail.getId() + " orderNo=" + orderNo);
						newOutOrders.setStatus(OutOrders.STATUS_OTHER);
						newDetail.setStatus(RepaymentDetail.STATUS_OTHER);
					}
					if(null != newDetail.getStatus()){
						repaymentDetailService.updateByPrimaryKeySelective(newDetail);
					}
					outOrdersService.updateByOrderNo(newOutOrders);
				}
			}
		} catch (Exception e) {
			logger.error("withhold error repaymentId=" + re.getId(), e);
			serviceResult = new ServiceResult("-100", "代扣失败");
		}
		return serviceResult;
	}*/

	/**
	 * 订单接口查询
	 */
	public void queryWithhold(RepaymentDetail detail) {
		try {

			// 查询订单的代扣方式
			OutOrders oo = outOrdersService.findByOrderNo(detail.getOrderId());
			if (oo != null) {
				Map map = new HashMap();
				map.put("orderNo", oo.getOrderNo());
				map.put("payDate", DateUtil.getDateFormat(detail.getCreatedAt(), "yyyyMMddHHmmss"));
				map.put("payCutType", oo.getOrderType());

				Map resultMap = PayQueryRoute.queryTransPay(map);
				String outerType = resultMap.get("payCutType").toString();// 代扣方式
				String retCode = resultMap.get("resp_code").toString();// 返回码

				String signParam = resultMap.get("qbm_signParam").toString();// 请求参数
				String reqParam = resultMap.toString();// 返回参数
				logger.error(outerType + "_QUERY_RESULT_PARAMS:" + signParam);

				logger.error(outerType + "_QUERY_ORDER_result:" + reqParam);

				if ("0000".equals(retCode)) { // 请求成功
					if (OutOrders.TYPE_BAOFOO.equals(oo.getOrderType())) {
						//进入宝付
						setQueryOrderBF(oo, reqParam, detail, resultMap);
					} else if (OutOrders.TYPE_RONGBAO.equals(oo.getOrderType())) {
						//进入融宝
						setQueryOrderRB(oo, reqParam, detail, resultMap);
					}

				}
			}
			}catch(Exception e){
				logger.error("query withhold error......", e);
				e.printStackTrace();
			}

		}

    @Override
    public List<HashMap<String, Object>> findBlackList(Map<String, Object> params) {

		return  repaymentDao.findBlackList(params);
    }

    /**
		 * 查询代扣 baofoo
		 * @param oo 订单信息
		 * @param reqParam 请求参数
		 * @param detail 代扣细节
		 * @param map 请求信息
		 */

	public void setQueryOrderBF(OutOrders oo, String reqParam, RepaymentDetail detail, Map map) {
		String orderStat = map.get("order_stat").toString();// 支付状态码
		//状态是I FF 不作处理
		if (!BaofooCutPayUtil.queryCodes.contains(orderStat)) {
			String resultPay = "";
			oo.setReturnParams(reqParam);
			oo.setOrderNo(detail.getOrderId());
			RepaymentDetail pd = new RepaymentDetail();
			pd.setId(detail.getId());

			if ("S".equals(orderStat)) {   // 支付成功
				oo.setStatus(OutOrders.STATUS_SUC);
				pd.setStatus(RepaymentDetail.STATUS_SUC);
				Repayment re = repaymentDao.selectByPrimaryKey(detail.getAssetRepaymentId());
				this.repay(re, detail);
			} else if ("I".equals(orderStat)) {   //支付失败
				oo.setStatus(OutOrders.STATUS_OTHER);
				pd.setStatus(RepaymentDetail.STATUS_OTHER);
			}
			repaymentDetailService.updateByPrimaryKeySelective(pd);
			outOrdersService.updateByOrderNo(oo);
		}

	}

	public void setQueryOrderRB(OutOrders oo, String reqParam, RepaymentDetail detail, Map map) {
		String string = map.get("batch_content").toString();
		String[] strings = string.split(",");
		String result_msg = strings[12];

		//状态是I FF 不作处理
		if (!result_msg.equals("处理中")) {
			String resultPay = "";
			oo.setReturnParams(reqParam);
			oo.setOrderNo(detail.getOrderId());
			RepaymentDetail pd = new RepaymentDetail();
			pd.setId(detail.getId());

			if (result_msg.equals("成功")) {   // 支付成功
				oo.setStatus(OutOrders.STATUS_SUC);
				pd.setStatus(RepaymentDetail.STATUS_SUC);
				Repayment re = repaymentDao.selectByPrimaryKey(detail.getAssetRepaymentId());
				this.repay(re, detail);
			} else if (result_msg.equals("失败")) {   //支付失败
				oo.setStatus(OutOrders.STATUS_OTHER);
				pd.setStatus(RepaymentDetail.STATUS_OTHER);
			}
			repaymentDetailService.updateByPrimaryKeySelective(pd);
			outOrdersService.updateByOrderNo(oo);
		}

	}

	/**
	 * 订单接口查询
	 */
/*
	public void queryWithhold(RepaymentDetail detail) {
		try {
			LianLianQueryResult ll = new LianLianQueryResult();
			ll.setDt_order(DateUtil.getDateFormat(detail.getCreatedAt(), "yyyyMMddHHmmss"));
			ll.setNo_order(detail.getOrderId());
			ll.setOid_partner(LianLianConstant.getOidPartner());
			// 加签
			String sginOrigin = LLPayUtil.genSignDataByJavaObject(ll);
			ll.setSign(RSAUtil.sign(LianLianConstant.getKey(), sginOrigin));
			String signParam = JSONUtil.beanToJson(ll);
			logger.error("LIANLIAN_QUERY_RESULT_PARAMS:" + signParam);

			String result = HttpUtil.getInstance().postJson(LianLianConstant.getQueryResult(), JSONUtil.beanToJson(ll));  //
			logger.error("LIANLIAN_QUERY_ORDER_result:" + result);
			JSONObject json = JSONObject.fromObject(result);
			String retCode = json.getString("ret_code");
			if ("0000".equals(retCode)) {   //请求成功
				String resultPay = json.getString("result_pay");
				OutOrders oo = new OutOrders();
				oo.setReturnParams(signParam);
				oo.setOrderNo(detail.getOrderId());
				RepaymentDetail pd = new RepaymentDetail();
				pd.setId(detail.getId());

				if ("SUCCESS".equals(resultPay)) {   // 支付成功
					oo.setStatus(OutOrders.STATUS_SUC);
					pd.setStatus(RepaymentDetail.STATUS_SUC);
					Repayment re = repaymentDao.selectByPrimaryKey(detail.getAssetRepaymentId());
					this.repay(re, detail);
				} else {   //支付失败
					oo.setStatus(OutOrders.STATUS_OTHER);
					pd.setStatus(RepaymentDetail.STATUS_OTHER);
				}
				repaymentDetailService.updateByPrimaryKeySelective(pd);
				outOrdersService.updateByOrderNo(oo);
			}
		} catch (Exception e) {
			logger.error("query withhold error......", e);
			e.printStackTrace();
		}

	}
*/
	@Override
	public void repay(Repayment re, RepaymentDetail detail) {
		BorrowOrder bo = new BorrowOrder();
		bo.setId(re.getAssetOrderId());
		Repayment copy = new Repayment();
		copy.setId(re.getId());
		copy.setRepaymentedAmount(re.getRepaymentedAmount() + detail.getTrueRepaymentMoney());

		User user = userDao.selectCollectionByUserId(re.getUserId());
		User userCopy = new User();
		userCopy.setId(user.getId());

		// 全部还清
		if (copy.getRepaymentedAmount() >= re.getRepaymentAmount()) {
			if (re.getLateDay() > 0) {
				copy.setStatus(BorrowOrder.STATUS_YQYHK);
				bo.setStatus(BorrowOrder.STATUS_YQYHK);
				// 逾期已还款 告知催收
				/*collection(user, re, detail, Repayment.REPAY_COLLECTION);*/
				try {
					jedisCluster.set("REPAY_" + re.getId(), "" + re.getId());
					jedisCluster.del("OVERDUE_" + re.getId());
					logger.error("collection repay success YQYHK REPAY_" + re.getId() + " value=" + jedisCluster.get("REPAY_" + re.getId()) + " OVERDUE=" + jedisCluster.get("OVERDUE_" + re.getId()));
				} catch (Exception e) {
					logger.error("collection repay error YQYHK repaymentId=" + re.getId(), e);
				}
			} else {
				copy.setStatus(BorrowOrder.STATUS_YHK);
				bo.setStatus(BorrowOrder.STATUS_YHK);
			}
			ThreadPool pool = ThreadPool.getInstance();
			pool.execute(new DtThread(UserPushUntil.PUSH_REPAYMENTSUCC, re.getUserId(), re.getAssetOrderId(), detail.getCreatedAt(), userService,
					pushUserService, borrowOrderService));
			if (User.CUSTOMER_NEW.equals(user.getCustomerType())) {
				userCopy.setCustomerType(User.CUSTOMER_OLD);
			}
			// 全部还款-更新info_user_info borrow_status 状态为不可见
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("USER_ID", user.getId());
			map.put("BORROW_STATUS", "0");
			// System.out.println("map=" + map + " 已还款，更新为不显示");
			indexDao.updateInfoUserInfoBorrowStatus(map);

			// 还款成功后提交催收
			copy.setRepaymentRealTime(null != detail.getCreatedAt() ? detail.getCreatedAt() : new Date());
			//通知p2p防止p2p重复扣款
			BorrowOrder borrow = borrowOrderService.findOneBorrow(re.getAssetOrderId());
			P2pUtils.finishOrder(borrow.getOutTradeNo(), System.currentTimeMillis());
		} else {
			if (re.getLateDay() > 0) {
				try {
					jedisCluster.set("OVERDUE_" + re.getId(), "" + re.getId());
					logger.error("collection repay success BFHK OVERDUE_" + re.getId() + " value=" + jedisCluster.get("REPAY_" + re.getId()));
				} catch (Exception e) {
					logger.error("collection repay error BFHK repaymentId=" + re.getId(), e);
				}
				// 逾期部分还款 告知催收
//				collection(user, re, detail, Repayment.BREPAY_COLLECTION);
			} else {
				copy.setStatus(BorrowOrder.STATUS_BFHK);
				bo.setStatus(BorrowOrder.STATUS_BFHK);
			}
		}

		// 还款金额
		Long money = detail.getTrueRepaymentMoney();
		// 已付的逾期费 = 所有还款金额 - 借款金额 - 手续费
		Long payedOver = copy.getRepaymentedAmount() - (re.getRepaymentInterest() + re.getRepaymentPrincipal());
		money = payedOver > 0 ? money - payedOver : money;
		if (money > 0) {
			// 把用户可借额度加上
			userCopy.setAmountAvailable(String.valueOf(Long.parseLong(user.getAmountAvailable()) + money));
			logger.error("用户额度变回成功userId=" + userCopy.getId() + ",amountAvailable=" + userCopy.getAmountAvailable());
		} else {
			logger.error("用户额度变回失败userId=" + userCopy.getId() + ",money=" + money + ",payedOver=" + payedOver + ",trueRepaymentMoney="
					+ detail.getTrueRepaymentMoney());
		}
		if (StringUtils.isNotBlank(userCopy.getCustomerType()) || StringUtils.isNotBlank(userCopy.getAmountAvailable())) {
			userDao.updateAmountAvailableByUserId(userCopy);
			logger.error("用户额度保存成功userId=" + userCopy.getId() + ",amountAvailable=" + userCopy.getAmountAvailable());
		} else {
			logger.error("用户额度保存失败userId=" + userCopy.getId() + ",customerType=" + userCopy.getCustomerType() + ",amountAvailable="
					+ userCopy.getAmountAvailable());
		}
		if (null != bo.getStatus()) {
			borrowOrderDao.updateByPrimaryKeySelective(bo);
		}
		repaymentDao.updateByPrimaryKeySelective(copy);
		
	}

	@Override
	public RepaymentAlipay saveByAlipayRepay(RepaymentAlipay alipay, Integer id) {
		boolean unRepayed = true;
		Long moneyAmountL = (long) (alipay.getMoneyAmount() * 100);
		List<Repayment> repayments = this.findRepayingByUserId(id);
		if (null == repayments) {
			alipay.setStatus(RepaymentAlipay.STATUS_FAIL);
			alipay.setRemark("该用户没有待还款的借款");
		} else {
			if (alipay.getAlipayRemark().contains("续期")) {
				alipay.setStatus(RepaymentAlipay.STATUS_FAIL);
				alipay.setRemark("备注包含续期，为待续期用户");
			} else {
				Calendar cal = Calendar.getInstance();
				cal.setTime(alipay.getRepayTime());
				long repayTimeL = cal.getTimeInMillis();
				for (Repayment re : repayments) {
					cal.setTime(re.getCreatedAt());
					long createAtL = cal.getTimeInMillis();
					// 有金额需要还，并且还款时间大于创建时间
					if (re.getRepaymentAmount() - re.getRepaymentedAmount() >= moneyAmountL && repayTimeL > createAtL) {
						RepaymentDetail detail = new RepaymentDetail();
						detail.setUserId(re.getUserId());
						detail.setAssetRepaymentId(re.getId());
						detail.setTrueRepaymentMoney(moneyAmountL);
						detail.setCreatedAt(alipay.getRepayTime());
						detail.setOrderId(alipay.getAlipayOrderNo());
						detail.setRepaymentType(RepaymentDetail.TYPE_ALIPAY);
						detail.setRemark("支付宝自动推送");
						detail.setStatus(RepaymentDetail.STATUS_SUC);
						if (re.getRepaymentAmount() - re.getRepaymentedAmount() == moneyAmountL) {
							alipay.setStatus(RepaymentAlipay.STATUS_SUC);
						} else {
							alipay.setStatus(RepaymentAlipay.STATUS_BF);
							alipay.setRemark("还完后金额未全部还完");
						}
						detail.setAssetOrderId(re.getAssetOrderId());
						repaymentDetailService.insertSelective(detail);
						this.repay(re, detail);
						tsOrdersService.sendBorrowStatus(re.getAssetOrderId());
						// 如果是未逾期的还款，调用提额
						if (re.getLateDay() == 0) {
							User user = userService.searchByUserid(re.getUserId());
							logger.error("repay to Mention Money ing ----------------->");
							borrowOrderService.addUserLimit(user);
						}

						alipay.setAssetRepaymentId(re.getId());
						alipay.setAssetRepaymentDetailId(detail.getId());
						unRepayed = false;
						break;
					}
				}
				if (unRepayed) {
					alipay.setStatus(RepaymentAlipay.STATUS_FAIL);
					alipay.setRemark("该用户没有可还款该金额、时间的借款");
				}
			}
		}
		return alipay;
	}

	/**
	 * 续期
	 *
	 * @param repayment
	 * @param record
	 * @return
	 */
	@Override
	public void renewal(Repayment repayment, RenewalRecord record) {
		if (null == repayment) {
			repayment = this.selectByPrimaryKey(record.getAssetRepaymentId());
		}
		// 更新续期为成功
		record.setStatus(RenewalRecord.STATUS_SUCC);
		renewalRecordDao.updateByPrimaryKeySelective(record);

		BorrowOrder borrowOrder = new BorrowOrder();
		borrowOrder.setId(repayment.getAssetOrderId());
		borrowOrder.setStatus(BorrowOrder.STATUS_HKZ);
		borrowOrderService.updateById(borrowOrder);

		Repayment re = new Repayment();
		// 如果申请续期成功
		re.setId(repayment.getId());
		re.setRepaymentAmount(repayment.getRepaymentAmount() - repayment.getPlanLateFee());
		re.setPlanLateFee(repayment.getRepaymentAmount().intValue() - repayment.getPlanLateFee());
		re.setPlanLateFee(0);
		re.setTrueLateFee(0);
		// 还款日期 延后 （逾期天数+续期天数）
		re.setRepaymentTime(DateUtil.addDay(repayment.getRepaymentTime(), record.getRenewalDay()));
		re.setLateFeeStartTime(null);
		re.setInterestUpdateTime(null);
		re.setLateDay(0);
		re.setRenewalCount(repayment.getRenewalCount() + 1);
		re.setStatus(BorrowOrder.STATUS_HKZ);
		re.setCollection(Repayment.COLLECTION_NO);
		this.updateRenewalByPrimaryKey(re);

		// 如果是已逾期的续期（调用催收同步）
		if (repayment.getStatus().equals(BorrowOrder.STATUS_YYQ)) {
			try {
				jedisCluster.set("RENEWAL_" + re.getId(), "" + re.getId());
				logger.error("collection renewal success RENEWAL_" + re.getId());
			} catch (Exception e) {
				logger.error("collection renewal error repaymentId=" + re.getId(), e);
			}
		}
	}

	@Override
	public void updateRenewalByPrimaryKey(Repayment re) {
		repaymentDao.updateRenewalByPrimaryKey(re);
	}

	/**
	 * 逾期
	 *
	 * @param re
	 */
	@Override
	public void overdue(Repayment re) {
		Date now = new Date();
		try {
			int between = DateUtil.daysBetween(re.getRepaymentTime(), now);
			User userT = new User();
			userT.setId(re.getUserId() + "");
			if (between > 0) {
				// 滞纳金 = （借款到账金额 + 服务费） * 滞纳金服务费 / 10000 * 滞纳天数
				Integer lateFee = (int) ((re.getRepaymentPrincipal() + re.getRepaymentInterest()) * re.getLateFeeApr() / 10000 * between);
				Integer maxLateFee = (int)(re.getRepaymentPrincipal()+re.getRepaymentInterest()) ;//滞纳金最大值(借款到账金额 + 服务费)
				if(lateFee>maxLateFee)
					lateFee = maxLateFee;
				// 更新用户最近一次逾期总天数、历史逾期总记录数
				User user = userService.selectCollectionByUserId(re.getUserId());
				if (re.getLateDay() == 0) {
					userT.setHistoryOverNum(String.valueOf(Integer.parseInt(user.getHistoryOverNum()) + 1));
					re.setLateFeeStartTime(now);
				}

				// 更新repay的
				re.setLateDay(between);
				re.setInterestUpdateTime(now);

				re.setPlanLateFee(lateFee);
				re.setRepaymentAmount(re.getRepaymentPrincipal() + re.getRepaymentInterest() + lateFee);
				if (between == 1) {
					re.setStatus(STATUS_YYQ);
					ThreadPool pool = ThreadPool.getInstance();
					pool.execute(new DtThread(UserPushUntil.PUSH_OVERDUESUCC, re.getUserId(), re.getAssetOrderId(), now, userService,
							pushUserService, borrowOrderService));
				}
				BorrowOrder borrowOrder = new BorrowOrder();
				borrowOrder.setId(re.getAssetOrderId());
				borrowOrder.setStatus(STATUS_YYQ);
				borrowOrderService.updateById(borrowOrder);

				// 如果未催收 进入催收
				if (Repayment.COLLECTION_NO == re.getCollection()) {
					try {
						jedisCluster.set("OVERDUE_" + re.getId(), String.valueOf(re.getId()));
						logger.error("collection overdue success OVERDUE_" + re.getId());
						re.setCollection(Repayment.COLLECTION_YES);
					} catch (Exception e) {
						logger.error("collection overdue error repaymentId=" + re.getId(), e);
					}
//					re = collection(user, re, null, Repayment.OVERDUE_COLLECTION);
					// re.setCollection(re.getCollection());
				}
				this.updateByPrimaryKeySelective(re);
			}
			userT.setLastOverDays(String.valueOf(between));
			userService.updateByPrimaryKeyUser(userT);
		} catch (ParseException e) {
			logger.error("overdue error repaymentId = " + re.getId(), e);
		}
	}

	/**
	 * 催收调用
	 *
	 * @param u  用户信息
	 * @param re 还款信息
	 * @return
	 */
	@Override
	public Repayment collection(User u, Repayment re, RepaymentDetail detail, int collType) {
		logger.error("collection applying userId = " + u.getId() + " - repaymentId " + re.getId());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		BorrowOrder bo = borrowOrderService.findOneBorrow(re.getAssetOrderId());

		List<Map> loanList = new ArrayList<Map>();

		Map<String, Object> loanMap = new HashMap<String, Object>();

		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("userId", u.getId());
		List<UserContacts> userContacts = userContactsService.selectUserContacts(params);
		// 应还本金
		int receivablePrinciple = re.getRepaymentAmount().intValue() - re.getPlanLateFee();
		// 实收的利息 = 已还金额 - 应还本金
		int realPenlty = re.getRepaymentedAmount().intValue() - receivablePrinciple;

		if (collType == Repayment.OVERDUE_COLLECTION) {
			// 紧急联系人
			List<Map> mmanUserRelas = new ArrayList<Map>();
			Map<String, String> mmanUserRela = new HashMap<String, String>();
			mmanUserRela.put("id", "");
			mmanUserRela.put("userId", u.getId());
			mmanUserRela.put("contactsKey", "1");
			mmanUserRela.put("relaKey", u.getFristContactRelation());
			mmanUserRela.put("infoName", u.getFirstContactName());
			mmanUserRela.put("infoValue", u.getFirstContactPhone());
			mmanUserRela.put("contactsFlag", "1");
			mmanUserRelas.add(mmanUserRela);

			mmanUserRela = new HashMap<String, String>();
			mmanUserRela.put("id", "");
			mmanUserRela.put("userId", u.getId());
			mmanUserRela.put("contactsKey", "2");
			mmanUserRela.put("relaKey", u.getSecondContactRelation());
			mmanUserRela.put("infoName", u.getSecondContactName());
			mmanUserRela.put("infoValue", u.getSecondContactPhone());
			mmanUserRela.put("contactsFlag", "1");
			mmanUserRelas.add(mmanUserRela);

			for (UserContacts contacts : userContacts) {
				mmanUserRela = new HashMap<String, String>();
				mmanUserRela.put("id", contacts.getId());
				mmanUserRela.put("userId", u.getId());
				mmanUserRela.put("contactsKey", "2");
				mmanUserRela.put("infoName", contacts.getContactName());
				mmanUserRela.put("infoValue", contacts.getContactPhone());
				mmanUserRelas.add(mmanUserRela);
			}

			loanMap.put("mmanUserInfo", u);
			loanMap.put("mmanUserRelas", mmanUserRelas);

			// 银行卡信息
			Map<String, Object> bankCard = new HashMap<String, Object>();
			params.put("limit", 1);
			List<UserCardInfo> userCardInfos = userBankService.findUserCardByUserId(params);
			if (null != userCardInfos && userCardInfos.size() > 0) {
				UserCardInfo cardInfo = userCardInfos.get(0);
				bankCard.put("id", cardInfo.getId());
				bankCard.put("userId", cardInfo.getUserId());
				bankCard.put("bankCard", cardInfo.getCard_no());
				bankCard.put("depositBank", cardInfo.getBankName());
				bankCard.put("mobile", cardInfo.getPhone());
			}

			loanMap.put("bankCard", bankCard);

			// 还款详情
			List<Map> creditLoanPayDetails = new ArrayList<Map>();
			List<RepaymentDetail> rds = this.findDetailsByRepId(re.getId());
			Map<String, Object> creditLoanPayDetail;
			for (RepaymentDetail rd : rds) {
				creditLoanPayDetail = new HashMap<String, Object>();
				creditLoanPayDetail.put("id", rd.getId());
				Map<String, Object> temp = new HashMap<String, Object>();
				temp.put("id", re.getId());
				creditLoanPayDetail.put("payId", temp);

				if (realPenlty <= 0) {
					creditLoanPayDetail.put("realMoney", rd.getTrueRepaymentMoney() / 100.00);
					creditLoanPayDetail.put("realPenlty", 0);

					creditLoanPayDetail.put("realPrinciple", (receivablePrinciple - re.getRepaymentedAmount()) / 100.00);
					creditLoanPayDetail.put("realInterest", re.getPlanLateFee() / 100.00);
				} else {
					creditLoanPayDetail.put("realMoney", (rd.getTrueRepaymentMoney() - realPenlty) / 100.00);
					creditLoanPayDetail.put("realPenlty", realPenlty / 100.00);

					creditLoanPayDetail.put("realPrinciple", 0);
					creditLoanPayDetail.put("realInterest", (re.getRepaymentAmount() - re.getRepaymentedAmount()) / 100.00);
				}
				creditLoanPayDetail.put("returnType", rd.getRepaymentType());
				creditLoanPayDetail.put("remark", rd.getRemark());

				creditLoanPayDetails.add(creditLoanPayDetail);
			}

			loanMap.put("creditLoanPayDetails", creditLoanPayDetails);
		}

		if (collType == Repayment.REPAY_COLLECTION || collType == Repayment.OVERDUE_COLLECTION || collType == Repayment.RENEWAL_COLLECTION) {

			// 借款信息
			Map<String, Object> mmanUserLoan = new HashMap<String, Object>();
			mmanUserLoan.put("id", bo.getId());
			mmanUserLoan.put("userId", u.getId());
			mmanUserLoan.put("loanPyId", bo.getOutTradeNo());
			mmanUserLoan.put("loanMoney", bo.getMoneyAmount() / 100.00);
			mmanUserLoan.put("loanRate", bo.getApr());
			mmanUserLoan.put("loanPenalty", re.getPlanLateFee() / 100.00);
			mmanUserLoan.put("loanPenaltyRate", bo.getLateFeeApr());
			mmanUserLoan.put("loanStartTime", sdf.format(re.getCreditRepaymentTime()));
			mmanUserLoan.put("loanEndTime", sdf.format(re.getRepaymentTime()));
			mmanUserLoan.put("loanStatus", re.getStatus());

			loanMap.put("mmanUserLoan", mmanUserLoan);
		}

		// 还款信息
		Map<String, Object> creditLoanPay = new HashMap<String, Object>();
		creditLoanPay.put("id", re.getId());
		Map<String, Object> temp = new HashMap<String, Object>();
		temp.put("id", bo.getId());

		creditLoanPay.put("loanId", temp);
		creditLoanPay.put("receivableStartdate", sdf.format(re.getCreditRepaymentTime()));
		creditLoanPay.put("receivableDate", sdf.format(re.getRepaymentTime()));
		creditLoanPay.put("receivableMoney", re.getRepaymentAmount() / 100.00);
		// creditLoanPay.put("receivablePrinciple", receivablePrinciple /
		// 100.00);
		// creditLoanPay.put("receivableInterest", re.getPlanLateFee() /
		// 100.00);
		creditLoanPay.put("realMoney", re.getRepaymentedAmount() / 100.00);
		if (realPenlty <= 0) {
			creditLoanPay.put("receivablePrinciple", (receivablePrinciple - re.getRepaymentedAmount()) / 100.00);
			creditLoanPay.put("receivableInterest", re.getPlanLateFee() / 100.00);
			creditLoanPay.put("realgetPrinciple", re.getRepaymentedAmount() / 100.00);
			creditLoanPay.put("realgetInterest", 0);
		} else {
			creditLoanPay.put("receivablePrinciple", 0);
			creditLoanPay.put("receivableInterest", (re.getRepaymentAmount() - re.getRepaymentedAmount()) / 100.00);
			creditLoanPay.put("realgetPrinciple", (re.getRepaymentedAmount().intValue() - realPenlty) / 100.00);
			creditLoanPay.put("realgetInterest", realPenlty / 100.00);
		}

		creditLoanPay.put("status", re.getStatus());

		loanMap.put("creditLoanPay", creditLoanPay);

		if (collType == Repayment.BREPAY_COLLECTION || collType == Repayment.REPAY_COLLECTION) {
			// 还款详情
			List<Map> creditLoanPayDetails = new ArrayList<Map>();
			Map<String, Object> creditLoanPayDetail;
			creditLoanPayDetail = new HashMap<String, Object>();
			creditLoanPayDetail.put("id", detail.getId());
			temp = new HashMap<String, Object>();
			temp.put("id", re.getId());
			creditLoanPayDetail.put("payId", temp);

			if (realPenlty <= 0) {
				creditLoanPayDetail.put("realMoney", detail.getTrueRepaymentMoney() / 100.00);
				creditLoanPayDetail.put("realPenlty", 0);

				creditLoanPayDetail.put("realPrinciple", (receivablePrinciple - re.getRepaymentedAmount()) / 100.00);
				creditLoanPayDetail.put("realInterest", re.getPlanLateFee() / 100.00);
			} else {
				creditLoanPayDetail.put("realMoney", (detail.getTrueRepaymentMoney() - realPenlty) / 100.00);
				creditLoanPayDetail.put("realPenlty", realPenlty / 100.00);

				creditLoanPayDetail.put("realPrinciple", 0);
				creditLoanPayDetail.put("realInterest", (re.getRepaymentAmount() - re.getRepaymentedAmount()) / 100.00);
			}
			creditLoanPayDetail.put("returnType", detail.getRepaymentType());
			creditLoanPayDetail.put("remark", detail.getRemark());

			creditLoanPayDetails.add(creditLoanPayDetail);

			loanMap.put("creditLoanPayDetails", creditLoanPayDetails);
		}

		loanList.add(loanMap);

		Map<String, Object> collectionRelevantJson = new HashMap<String, Object>();
		collectionRelevantJson.put("collectionRelevantJson", loanList);

		// 设置参数 可设置多个
		List<NameValuePair> postParams = new ArrayList<NameValuePair>();
		postParams.add(new BasicNameValuePair("collectionRelevantJson", JSONObject.fromObject(collectionRelevantJson).toString()));
		try {
			String result = HttpUtil.getInstance().post(CollectionConstant.getCollectionPath(), postParams);
			JSONObject obj = JSONObject.fromObject(result);
			if (obj.getString("code").equals("0")) {
				re.setCollection(Repayment.COLLECTION_YES);
			}
		} catch (Exception e) {
			logger.error("collection error", e);
		}
		return re;
	}

	@Override
	public List<Repayment> findAllByBorrowId(Integer borrowId) {
		return repaymentDao.findAllByBorrowId(borrowId);
	}

	@Override
	public boolean insertByBorrorOrder(BorrowOrder borrowOrder) {
		try {
			Date fkDate = borrowOrder.getLoanTime();
			Repayment repayment = new Repayment();
			repayment.setUserId(borrowOrder.getUserId());
			repayment.setAssetOrderId(borrowOrder.getId());
			repayment.setRepaymentAmount(Long.valueOf(borrowOrder.getMoneyAmount()));
			repayment.setLateFeeApr(borrowOrder.getLateFeeApr());
			repayment.setRepaymentedAmount(0L);
			repayment.setRepaymentPrincipal(Long.valueOf(borrowOrder.getIntoMoney()));
			repayment.setRepaymentInterest(Long.valueOf(borrowOrder.getLoanInterests()));

			repayment.setFirstRepaymentTime(DateUtil.addDay(fkDate, borrowOrder.getLoanTerm()));// 放款时间加上借款期限
			repayment.setRepaymentTime(DateUtil.addDay(fkDate, borrowOrder.getLoanTerm()));// 放款时间加上借款期限
			repayment.setCreditRepaymentTime(fkDate);
			// repayment.setCreatedAt(fkDate);
			// repayment.setUpdatedAt(fkDate);
			repayment.setStatus(borrowOrder.getStatus());
			repaymentDao.insertSelective(repayment);
			//地推 借款成功
			ThreadPool pool = ThreadPool.getInstance();
			pool.execute(new DtThread(UserPushUntil.PUSH_BORROWSUCC, repayment.getUserId(), repayment.getAssetOrderId(), fkDate, userService,
					pushUserService, borrowOrderService));
			final String userPhone = borrowOrder.getUserPhone();
			final double intoMoney = (borrowOrder.getIntoMoney() / 100.00);
			ThreadPool3.getInstance().run(new Runnable() {
				@Override
				public void run() {
					SendSmsUtil.sendSmsDiyCL(userPhone, "你收到贷速侠打款" + intoMoney + "元,预计很快到账，请注意查收！");
				}
			});
		} catch (Exception e) {
			logger.error("create repayment insertByBorrorOrder", e);
		}

		// //借款成功
		// try{
		// //生成大抽奖的抽奖码
		// HashMap<String,String> stepMap=new HashMap<String,String>();
		// stepMap.put("userPhone", borrowOrder.getUserPhone());
		// stepMap.put("awardType", "BORROW");
		// logger.error("addUserStep   BORROW  请求参数："+stepMap.toString());
		// ServiceResult serviceResult=
		// jsStepRecordService.addUserStep(stepMap);
		// logger.error("addUserStep 抽奖返回>>>："+serviceResult.getCode()+":"+serviceResult.getMsg());
		// }catch (Exception e) {
		// logger.error("addUserStep error BORROW",e);
		// }

		return true;
	}

	/**
	 * 富友支付封装
	 *
	 * @return
	 */
	@Override
	public Map<String, String> payAction(User user, UserCardInfo info, MobilePaySend paySend, Long money, String act) {
		String orderNo = GenerateNo.getUUID();
		Map<String, String> params = null;
		paySend.setMCHNTCD(FuYouConstant.getMchntcd());
		paySend.setTYPE(FuYouConstant.TYPE);
		paySend.setVERSION(FuYouConstant.VERSION);
		paySend.setLOGOTP(FuYouConstant.LOGOTP);
		paySend.setMCHNTORDERID(orderNo);
		paySend.setUSERID(user.getId());
		paySend.setAMT(String.valueOf(money));
		paySend.setBANKCARD(info.getCard_no());
		paySend.setNAME(user.getRealname());
		paySend.setIDTYPE(FuYouConstant.IDTYPE);
		paySend.setIDNO(user.getIdNumber());
		paySend.setSIGNTP(FuYouConstant.SIGNTP);
		paySend.setSIGN(paySend.toSign());
		String reply_mesg = null;
		try {
			params = new HashMap<String, String>();
			reply_mesg = XmlUtil.toXml(MobilePaySend.class, paySend);
			params.put("FM", DESCoderFUIOU.desEncrypt(reply_mesg, DESCoderFUIOU.getKeyLength8(FuYouConstant.getKey())));
			params.put("ENCTP", FuYouConstant.ENCTP_YES);
			params.put("VERSION", FuYouConstant.VERSION);
			params.put("MCHNTCD", FuYouConstant.getMchntcd());
			params.put("ORDERNO", orderNo);

			OutOrders outOrders = new OutOrders();
			outOrders.setUserId(user.getId());
			outOrders.setOrderType(OutOrders.TYPE_FUYOU);
			outOrders.setOrderNo(orderNo);
			outOrders.setAct(act);
			outOrders.setReqParams(params.toString());
			outOrdersService.insert(outOrders);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return params;
	}

	@Override
	public int findParamsCount(HashMap<String, Object> params) {
		return repaymentDao.findParamsCount(params);
	}

	@Override
	public Repayment selectByAssetOrderId(Integer assetOrderId) {
		// TODO Auto-generated method stub
		return repaymentDao.selectByAssetOrderId(assetOrderId);
	}

	@Override
	public List<Repayment> findAll2(HashMap<String, Object> params) {
		
		return repaymentDao.findParams(params);
	}

}
